package HibernateMapping;

import java.util.Date;

import org.hibernate.Session;
import org.hibernate.Transaction;

public class Tweet {

	private int id;
	private String text;
	private Date dateTime;
	private int retweetCount;
	private User user;
	private Keyword keyword;

	private Tweet(String text, Date dateTime, int retweetCount,
			User user, Keyword keyword) {

		this.text = text;
		this.dateTime = dateTime;
		this.retweetCount = retweetCount;
		this.user = user;
		this.keyword = keyword;
	}

	public static Tweet addTweet(String text, Date dateTime, int retweetCount,
			User user, Keyword keyword) {
		if ((user == null) || (keyword == null)) {
			return null;
		}
		
		Transaction tms = null;
		Session session = HibernateUtil.getSessionFactory().openSession();

		Tweet temp = null;
		
		try {
			tms = session.beginTransaction();

			temp = new Tweet(text, dateTime, retweetCount, user, keyword);
			session.save(temp);
			if (!tms.wasCommitted())
				tms.commit();
		} catch (RuntimeException e) {
			if (tms != null) {
				tms.rollback();
			}
			e.printStackTrace();
		} finally {
			//session.flush();
			session.close();
		}

		return temp;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public Date getDateTime() {
		return dateTime;
	}

	public void setDateTime(Date dateTime) {
		this.dateTime = dateTime;
	}

	public int getRetweetCount() {
		return retweetCount;
	}

	public void setRetweetCount(int retweetCount) {
		this.retweetCount = retweetCount;
	}

	public User getUser() {
		return user;
	}

	public Keyword getKeyword() {
		return keyword;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public void setKeyword(Keyword keyword) {
		this.keyword = keyword;
	}
}
